<?php

namespace app\company\controller;

use app\company\service\DepartmentService;
use app\company\service\EmployeeService;
use app\company\service\PositionService;
use app\company\validate\EmployeeAddValidate;
use app\exception\MsgException;
use app\model\UserModel;
use support\Request;
use support\Response;
use Throwable;

/**
 * 员工管理
 * @api
 */
class Employee extends Base
{

    /**
     * 获取表格数据
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function lists(Request $request): Response
    {
        $params = $request->all();
        $service = new EmployeeService();

        $params['cid'] = $this->getPayload('cid');
        $list = $service->getList($params);
        return $this->withData(0, 'success', $list);
    }

    /**
     * 新增
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function add(Request $request): Response
    {
        $data = $request->all();

        //查询用户
        if(!empty($data['query_user'])){
            $userInfo = UserModel::where('mobile', $data['query_user'])
                ->field('id,realname,avatar,register_time')
                ->find();
            return $this->withData(0, 'success', $userInfo);
        }
        $data['cid'] = $this->getPayload('cid');
        $data['dept_id'] = end($data['dept_id']);

        //表单验证
        $validate = new EmployeeAddValidate();
        if (!$validate->check($data)) {
            throw new MsgException($validate->getError());
        }

        $service = new EmployeeService();

        $res = $service->add($data);
        return $this->withData(0, '新增成功', $res);
    }

    /**
     * 编辑
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function edit(Request $request): Response
    {
        $data = $request->all();
        $service = new EmployeeService();
        $data['cid'] = $this->getPayload('cid');

        //获取信息
        if($request->method() == 'GET'){
            //可用职位列表
            $positions = (new PositionService)->getList([
                'cid' => $data['cid'],
                'pageSize' => 1000
            ]);
            //可用部门列表
            $depts = (new DepartmentService())->getList([
                'cid' => $data['cid']
            ]);
            return $this->withData(0, 'success', [
                'positions' => $positions,
                'depts' => $depts,
                'cid' => $data['cid']
            ]);
        }

        if(empty($data['id'])){
            throw new MsgException("编辑数据需传入ID");
        }

        //密码转md5
        if(!empty($data['password'])){
            $data['password'] = md5($data['password']);
        }else{
            unset($data['password']);
        }
        $res = $service->edit($data);
        return $this->withData(0, '编辑成功', $res);
    }

}